package utils;

import java.net.URL;

import com.google.gdata.client.Query;
import com.google.gdata.client.contacts.ContactsService;
import com.google.gdata.data.contacts.ContactEntry;
import com.google.gdata.data.contacts.ContactFeed;
import com.google.gdata.data.extensions.Email;

public class UserRoles {
	private boolean bADM;
	private boolean bEXE;
	private boolean bEXP;
	private boolean bMOR;
	private boolean bMPS;
	private boolean bNOM;
	private boolean bSGM;
	
	private ContactsService myService;

	public UserRoles(String EmailID) {

		try {
			String strContactServiceName = System
					.getProperty("CONTACTSERVICES");
			String strUserName = System.getProperty("ROLES_USERNAME");
			String strPwd = System.getProperty("ROLES_PWD");

			myService = new ContactsService(strContactServiceName);
			myService.setUserCredentials(strUserName, strPwd);

			URL feedUrl = new URL(System.getProperty("ROLES_FEED_URL"));
			bADM = getUserRoles(EmailID,
					System.getProperty("ROLES_ADM_GROUP_URL"), myService,
					feedUrl);
			bEXE = getUserRoles(EmailID,
					System.getProperty("ROLES_EXE_GROUP_URL"), myService,
					feedUrl);			
			bEXP = getUserRoles(EmailID,
					System.getProperty("ROLES_EXP_GROUP_URL"), myService,
					feedUrl);
			bMOR = getUserRoles(EmailID,
					System.getProperty("ROLES_MOR_GROUP_URL"),
					myService, feedUrl);
			bMPS = getUserRoles(EmailID,
					System.getProperty("ROLES_MPS_GROUP_URL"),
					myService, feedUrl);
			bNOM = getUserRoles(EmailID,
					System.getProperty("ROLES_NOM_GROUP_URL"),
					myService, feedUrl);
			bSGM = getUserRoles(EmailID,
					System.getProperty("ROLES_SGM_GROUP_URL"),
					myService, feedUrl);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public boolean getUserRoles(String EmailID, String strGroup_URLID,
			ContactsService myService, URL feedUrl) {

		try {
			Query myQuery = new Query(feedUrl);
			myQuery.setStringCustomParameter("group", strGroup_URLID);
			ContactFeed resultFeed = myService
					.query(myQuery, ContactFeed.class);

			// Iterate and match the email ID
			for (int i = 0; i < resultFeed.getEntries().size(); i++) {
				ContactEntry entry = resultFeed.getEntries().get(i);
				for (Email email : entry.getEmailAddresses()) {
					if (EmailID.equals(email.getAddress().toLowerCase())) {
						return true;
					}
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return false;
	}

	public boolean isADM() {
		return bADM;
	}

	public boolean isEXE() {
		return bEXE;
	}	

	public boolean isEXP() {
		return bEXP;
	}
	
	public boolean isMOR() {
		return bMOR;
	}
	
	public boolean isMPS() {
		return bMPS;
	}
	
	public boolean isNOM() {
		return bNOM;
	}
	
	public boolean isSGM() {
		return bSGM;
	}
}
